import { clearToken } from '@/utils/token'
import {
  Button,
  List,
  DatePicker,
  NavBar,
  Toast,
  Popup,
  Dialog,
} from 'antd-mobile'
import classNames from 'classnames'
import { useHistory } from 'react-router-dom'
import { useEffect, useRef, useState } from 'react'
import { useDispatch, useSelector } from 'react-redux'
import styles from './ProfileEdit.module.scss'
import {
  getUserProfile,
  updateUserProfile,
  updateUserPhoto,
} from '@/store/actions/user'
import { RootState } from '@/types/store'
import { useInitialState } from '@/utils/use-initial-state'
import { EditInput } from './EditInput/EditInput'
import { EditList } from './EditList/EditList'
import dayjs from 'dayjs'
import { logout } from '@/store/actions/login'

export const ProfileEdit = () => {
  // hooks
  const history = useHistory()
  const dispatch = useDispatch()

  // 用户其他信息
  // const profile = useSelector((state: RootState) => state.user.profile)
  // 获取用户其它信息
  // useEffect(() => {
  //   dispatch(getUserProfile())
  // }, [dispatch])
  // 使用自定义hooks获取用户状态
  const profile = useInitialState(getUserProfile, 'user').profile

  const out = () => {
    Dialog.show({
      title: '温馨提示',
      content: '亲，确定要退出登录吗？',
      // 是否支持点击遮罩关闭对话框
      closeOnMaskClick: true,
      // 点击操作按钮后后是否关闭
      closeOnAction: true,
      // 操作按钮列表，可以传入二级数组来实现同一行内并排多个按钮
      actions: [
        [
          { key: 'cancel', text: '取消', style: { color: '#999' } },
          {
            key: 'confirm',
            text: '确定',
            onClick: () => {
              dispatch(logout())
              Toast.show({
                content: '成功退出!',
                duration: 1000,
              })
              history.replace('/login')
            },
            style: { color: 'red' },
          },
        ],
      ],
    })
  }

  const [inputVisible, setInputVisible] = useState(false)

  // 修改组件显示事件处理
  const handleInputVisible = (visible: any) => {
    setInputVisible(true)
    // console.log(visible)
  }

  // 父组件定义的函数，用来接受新的昵称
  const onValueSubmit = async (value: string, prop: string) => {
    // console.log('修改后的prop', prop)
    // console.log('修改后的value', value)
    // prop 的来回传递是为了复用这个 action
    if (prop === 'photo') {
      // 模拟用户点击
      touXiang.current?.click()
    } else {
      await dispatch(updateUserProfile({ [prop]: value }))
      // 提示用户修改昵称完毕
      if (prop === 'name') {
        Toast.show({
          content: `昵称更新成功`,
          duration: 1000,
        })
      } else if (prop === 'intro') {
        Toast.show({
          content: `简介更新成功`,
          duration: 1000,
        })
      } else if (prop === 'gender') {
        Toast.show({
          content: `性别更新成功`,
          duration: 1000,
        })
      }
    }
    // 关闭弹窗
    setPopupState({
      prop,
      value,
      visible: false,
    })
  }

  const [popupState, setPopupState] = useState({
    prop: '', // 新增点击的是谁：昵称？简介？。取值：name、intro
    value: '', // 编辑的内容
    visible: false, // 原来的弹窗是否可见标志
  })

  // 创建原生DOM容器
  const touXiang = useRef<HTMLInputElement>(null)
  // 更换头像
  const handlePhotoChange = async (e: React.ChangeEvent<HTMLInputElement>) => {
    // 拿到file对象
    console.log(e)
    // 非空判断
    if (!e.target.files) return
    // 创建表单对象
    const formData = new FormData()
    // 拼装组件表单对象
    formData.append('photo', e.target.files[0])
    // dispatch action
    await dispatch(updateUserPhoto(formData))

    // 关闭弹窗
    setPopupState({
      prop: 'photo',
      value: 'cancel',
      visible: false,
    })
    Toast.show({
      content: `头像更新成功`,
      duration: 1000,
    })
  }

  // 出生日期选择状态
  const [birthday, setBirthday] = useState(false)
  // 处理选择出生日期
  const handleBirthday = async (date: Date) => {
    const birthday = dayjs(date).format('YYYY-MM-DD')
    // 提交给服务器更新
    await onValueSubmit(birthday, 'birthday')
    // 提示用户
    Toast.show({ content: '生日更新成功', duration: 600 })
    // 隐藏生日选择框
    setBirthday(false)
  }
  return (
    <div className={styles.root}>
      <div className="content">
        {/* 标题 */}
        <NavBar onBack={history.goBack}>个人信息</NavBar>

        <div className="wrapper">
          {/* 列表 */}
          <List className="profile-list">
            {/* 列表项 */}
            <List.Item
              onClick={() =>
                setPopupState({
                  prop: 'photo',
                  value: profile.photo,
                  visible: true,
                })
              }
              extra={
                <span className="avatar-wrapper">
                  <img
                    width={24}
                    height={24}
                    src={
                      profile.photo ??
                      'http://toutiao.itheima.net/images/user_head.jpg'
                    }
                    alt="头像🐖"
                  />
                </span>
              }
              arrow>
              头像
            </List.Item>
            <List.Item
              arrow
              extra={profile.name}
              // 使用时必须传入 prop: 'name', 对应的属性，便于后续区分
              onClick={() =>
                setPopupState({
                  prop: 'name',
                  value: profile.name,
                  visible: true,
                })
              }>
              昵称
            </List.Item>
            <List.Item
              arrow
              extra={
                <span className={classNames('intro', 'normal')}>
                  {profile.intro || '未填写'}
                </span>
              }
              onClick={() =>
                setPopupState({
                  prop: 'intro',
                  value: profile.intro,
                  visible: true,
                })
              }>
              简介
            </List.Item>
          </List>

          <List className="profile-list">
            <List.Item
              arrow
              extra={profile.gender + '' === '0' ? '男' : '女'}
              onClick={() => {
                setPopupState({
                  prop: 'gender',
                  value: profile.gender + '',
                  visible: true,
                })
              }}>
              性别
            </List.Item>
            <List.Item
              arrow
              extra={profile.birthday}
              onClick={() => setBirthday(true)}>
              生日
            </List.Item>
          </List>

          <DatePicker
            visible={birthday}
            onCancel={() => setBirthday(false)}
            value={new Date(profile.birthday)}
            title="选择年月日"
            min={new Date(1900, 0, 1, 0, 0, 0)}
            max={new Date()}
            onConfirm={handleBirthday}
          />
        </div>

        <div className="logout">
          <Button className="btn" onClick={out}>
            退出登录
          </Button>
        </div>
      </div>
      {/* 编辑昵称/简介 */}
      <Popup
        visible={
          (popupState.prop === 'name' && popupState.visible) ||
          (popupState.prop === 'intro' && popupState.visible)
        }
        position={'right'}
        // 表示在关闭弹出层时，销毁组件内容
        // destroyOnClose
      >
        {/* 利用key的特殊性解决内容显示bug */}
        <EditInput
          key={popupState.prop}
          value={popupState.value}
          prop={popupState.prop}
          onClose={(value, prop) =>
            setPopupState({
              value,
              prop,
              visible: false,
            })
          }
          onValueSubmit={onValueSubmit}
        />
      </Popup>
      {/* 修改性别 */}
      <Popup
        visible={
          (popupState.prop === 'gender' && popupState.visible) ||
          (popupState.prop === 'photo' && popupState.visible)
        }
        onMaskClick={() =>
          setPopupState({
            prop: popupState.prop,
            value: 'cancel', // 更语言义化
            visible: false,
          })
        }>
        <EditList
          value={popupState.value}
          prop={popupState.prop}
          onClose={(value, prop) =>
            setPopupState({
              value: value,
              prop: prop,
              visible: false,
            })
          }
          onValueSubmit={onValueSubmit}
        />
      </Popup>
      <div className="wrapper">
        <input type="file" hidden ref={touXiang} onChange={handlePhotoChange} />
      </div>
    </div>
  )
}
